<!-- mod by luoji  all file -->
<template>
  <a-modal
    v-model="visible"
    :title="'发起比价'"
    :maskClosable="false"
    :keyboard="false"
    :confirmLoading="confirmLoading"
    :destroyOnClose="true"
    :width="700"
    @ok="ok"
    @cancel="close"
  > 
    <div class="popWindow" v-if="isRouterAlive||true">
      <a-row>
        <a-col :span="4">项目登记名称</a-col>
        <!-- <a-col :span="7">
          <a-input v-model="projectName"/>
        </a-col> -->
          <a-col :span="8">
          <!-- <a-input v-model="projectName"/>
           -->
            <a-auto-complete
            v-model="projectName"
            :data-source="dataSource"
            allowClear
            placeholder="请输入"
            @select="onSelect"
            @search="onSearch"
            @change="onChange"
        />
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="4">
          截止日期
        </a-col>
        <a-col :span="17">
          <a-date-picker
           v-model="date"/>
        </a-col>
        <a-col :span="3">
          <a-button type="primary" v-if="list.length < 10" @click="addLine">添加供应商</a-button>
        </a-col>
      </a-row>
      <a-row class="popWindow_row popHeader">
        <a-col :span="7">供应商</a-col>
        <a-col :span="7">联系人</a-col>
        <a-col :span="7">手机号</a-col>
      </a-row>
      <a-row class="popWindow_row" v-for="(item,index) in list" :key="index"> 
        <a-col :span="7">
          <staff-selector
            v-model="item.a"
            :options="taffSelectorOpts"
            @change="onValueChange(item)"
          >
          </staff-selector>
        </a-col>
        <a-col :span="7">
          <a-input v-model="item.b"/>
        </a-col>
        <a-col :span="7">
          <a-input v-model="item.c"/>
        </a-col>
        <a-col :span="3">
          <a-button type="danger" @click="delLine(index)">删除行</a-button>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
        </a-col>
      </a-row>
    </div>
  </a-modal>
</template>

<script lang="ts">

import {
  Component, Vue, Prop, Watch
} from 'vue-property-decorator';

import {
  Modal,
  Row,
  Col,
  Input,
  Select,
  Alert
} from '@h3/antd-vue';
import { AutoComplete } from "@h3/antd-vue";
import StaffSelector from "@cloudpivot/form/src/renderer/components/shared/staff-selector.vue";
import Axios from 'axios';
import { userApi } from "@cloudpivot/api";
import moment from 'moment';



// 查询项目名称api定义
const api: any = {
  getSubject: '/api/subject/getSubject'
};


@Component({
  name: 'form-modify-compare-price',
  components: {
    AModal: Modal,
    ARow: Row,
    ACol: Col,
    Alert,
    ATextarea: Input.TextArea,
    AAutoComplete: AutoComplete,
    ASelect: Select,
    ASelectOption: Select.Option,
    StaffSelector
  }
})
export default class FormComparePriceModal extends Vue {
  list: Array<any> = [
  ]
  dataSource: any[] = []; //模糊搜索的数据源
  dataList: any[] = []
  date: any = null;
  projectName :any ="";
  projectCode  :any ="";

  visible: boolean = false;

  confirmLoading: boolean = false;
  action: any = "";
  isRouterAlive: boolean = true;
  layout: any = {
    left: 6,
    right: 18
  }

  taffSelectorOpts: any = {
    selectOrg: false,
    selectUser: true,
    showModel: true,
    mulpitle: false,
    showSelect: true,
    placeholder: '请选择',
    title: '选择供应商',
    rootNode: [{ id : '8aeec3a67ae6cf45017aeff3dcf915d6'}]
  }


  async onSearch(searchText) {
    const res: any = await this.getProjectList(searchText);
    if(res) {
        if(res.errcode === 0){
            this.dataList = res.data
            this.dataSource  = res.data.map(item=>{
                return item.projectName
            })
        }
    }
  }
  onSelect(val) {
      this.getprojectCode(val)
  }

  getprojectCode(val:any){
     const codeList =  this.dataList.filter(item=>item.projectName === val)
     this.projectCode = codeList ? codeList[0].projectCode: ''  
     if(!val){
         this.onSearch('')
     }
  }

  onChange(val) {
    this.getprojectCode(val)
   
  }
  // 查询项目名称
  getProjectList(wd) {
    return new Promise(resolve => {
       Axios.get(api.getSubject, {
           params: {
            subjectName: wd,
           }
       })
      .then(res => {
        resolve(res);
      });
    });
  }


  async init(num: number, action: any) {
    this.action = action;
    this.list = []
    let user: any = window.sessionStorage.getItem('user');

      if (user) {

        user = JSON.parse(user);

      } else {

        user = { id:'',name:'' };

      }
      //不默认
      // if(user.id != '' && user.id != null && user.id.length > 0){
      //   var item = { 
      //     a: [{
      //       type: 1, //1部门，3人员
      //       imgUrl: '//www.baidu.com/img1.png',
      //       name:'',
      //       id: user.id,
      //       departmentId : '' ,
      //       departments : [] 
      //     }]
      //   }
      //   var userinfo = await userApi.getUserInfo(user.id);
      //   if(userinfo && userinfo.errcode === 0) { 
      //     item.a[0].departmentId = userinfo.data.departmentId;
      //     item.a[0].name = userinfo.data.name;
      //     item.b = userinfo.data.name
      //     item.c = userinfo.data.mobile
      //     this.reload();
      //   }
      //   this.list.push(item);
      // }
      this.onSearch('')
      var t = new Date();
      this.date = t.getFullYear() + '-' + (t.getMonth()+1) + '-' + t.getDate();
    this.show();
  }
  show() {
    this.visible = true;
  }

 //表单数据重置
  resetform(){
      this.projectCode = ''
      this.projectCode = ''
  }

  close() {
    this.confirmLoading = false;
    this.visible = false;
  }

  ok() {
    var idsStr=sessionStorage.getItem("sessionKey");
    let arr: any = null;
    if(idsStr){
      arr =idsStr.split(',');
     }
    var suppliers:any =[];
    var projectName = this.projectName;
    var projectCode = this.projectCode;

    //循环插入数据
    if(this.list.length==0){
      alert("请选择供应商");
      return;
    }else{
      for(var i=0;i<this.list.length;i++){
          var newparams :any= {};
          newparams.id=this.list[i].a[0].id;
          newparams.phone=this.list[i].c;
          newparams.contacts=this.list[i].b;
          newparams.supplier=this.list[i].a[0].name;
          suppliers.push(newparams);
      }
    }
    if(projectName==""){
      alert("项目名称必填");
      return;
    }
    var sessionCode=sessionStorage.getItem("sessionCode");
    var ajaxurl="";
    switch(sessionCode)
    {
      case "CYCLWPXQC":
        ajaxurl="/api/materials/addInvitation";
        break;
      case "BPCG":
        ajaxurl="/api/invitation/addInvitation";
        break;
      case "DZBGXQC":
        ajaxurl="/api/bigAnt/addInvitation";
        break;
      case "DCCGHTSQ":
        ajaxurl="/api/dccght/addInvitation";
        break;
      case "XBJXQC":
        ajaxurl="/api/xbjxqc/addInvitation";
        break;
    }
    Axios.post(ajaxurl,{
      expirationDate: this.date,
      //expirationDate: "2021-08-04 00:00:00",
      type: "询价",
      ids: arr, 
      suppliers: suppliers,
      projectCode: projectCode,
      projectName: projectName,
      }).then((res:any)=>{
        debugger;
        if(res.errmsg!="SUCCESS"){
          alert("报价信息生成失败");
        }else{
          this.close();
        }
      });
    console.log(this.date, this.list)
  }

  delLine(index){
    this.list.splice(index, 1);
  }
  
  addLine(){
    this.list.push({});
  }

  onValueChange(item : any){
    if(item.a.length > 0){
      item.b = item.a[0].extend2;
      item.c = item.a[0].mobile;
    }
  }

  async getUserInfo(userId: string, item: any){
    const res: any = await userApi.getUserInfo(userId);
    if(res && res.errcode === 0) {
      item.a[0].departmentId = res.data.departmentId;
      item.a[0].name = res.data.name;
      item.b = res.data.name
      item.c = res.data.mobile
      this.reload();
    }else{
      this.$message.error(res.errmsg);
    }
  }

  reload(){
      this.isRouterAlive=false;
      this.$nextTick(function(){
        this.isRouterAlive=true;
      })
    }
}
</script>

<style lang="less" scoped>
    .popWindow .ant-col{
      padding: 2px !important;
    }

    .popWindow .popHeader{
      margin-top: 10px;
      padding: 5px 8px;
      border-top: 1px solid #DDD;
    }

    .popWindow .popWindow_row{
      border-bottom: 1px solid #DDD;
    }
</style>
